/**
 * filename: SaveUserInfoForLogined.java
 * author: luruifeng
 * date: 2016年3月2日
 * http: <a href='http://www.anzeinfo.com'>www.anzeinfo.com</a>
 * Copyright (c) 2016 Anze, Inc. All rights reserved.
 */
package com.anze.abd.spring.security;

import java.util.Collection;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

import com.anze.abd.constant.MyConstant;
import com.anze.abd.persistence.domain.UserInfo;
import com.anze.abd.service.userinfo.UserInfoService;
import com.anze.base.constant.BaseConstant;
import com.anze.base.log.Log4jUtils;
import com.anze.base.persistence.domain.User;
import com.anze.base.spring.security.AuthenticationSuccessEvent;

/**
 * 登录成功后保存用户信息
 * @author luruifeng 2016年3月2日
 * @version 2.4
 * @since 2.4 2016年3月2日
 */
@Component("saveUserInfoForLogined")
public class SaveUserInfoForLogined implements AuthenticationSuccessEvent {

	private Log log = Log4jUtils.getLog(SaveUserInfoForLogined.class);

	@Resource(name = "userInfoService")
	private UserInfoService userInfoService;

	@Override
	public void onSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws Exception {
		String name = authentication.getName();
//		String password = authentication.getCredentials().toString();
		WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
		String ip = details.getRemoteAddress();
		String sessionId = details.getSessionId();
		Collection<? extends GrantedAuthority> authoritys = authentication.getAuthorities();
		log.debug("=====用户信息====== name:" + name/* + ", password:" + password*/ + ", ip:" + ip + ", sessionId:" + sessionId
				+ ", roles:" + authoritys.toString());

		User user = (User) request.getSession().getAttribute(BaseConstant.SESSION_USER);
		UserInfo userInfo = userInfoService.getByUser(user);
		if (null != userInfo) {
			request.getSession().setAttribute(MyConstant.SESSION_USERINFO, userInfo);
		}
	}

}
